package com.greateamd.timetableasy.client.widgets.cursus;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiConstructor;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.greateamd.timetableasy.client.services.cursus.CursusService;
import com.greateamd.timetableasy.client.services.cursus.CursusServiceAsync;
import com.greateamd.timetableasy.client.services.util.ServerCall;
import com.greateamd.timetableasy.client.widgets.ListBox;
import com.greateamd.timetableasy.domain.Cursus;

public class CursusListBox extends ListBox 
{
	private List<Cursus> cursuses;
	
	public @UiConstructor CursusListBox(boolean autoLoad,boolean multi) {
		super(multi);
		if(autoLoad){
			loadCursus();
		}
	}	

	public void loadCursus() {
		final CursusServiceAsync cursusService = GWT.create(CursusService.class);
		new ServerCall<List<Cursus>>() {

			@Override
			protected void callService(AsyncCallback<List<Cursus>> asyncCallback) {
				cursusService.getAll(asyncCallback);
			}

			@Override
			public void onSuccess(List<Cursus> list) {
				cursuses = list;
				showList();
			}
		}.call();
	}

	protected void showList() {
		clear();
		for(Cursus cursus : cursuses){
			addItem(cursus.getName());
		}
	}
	
	public Cursus getSelectedCursus(){
		if(getSelectedIndex()!= -1){
			return cursuses.get(getSelectedIndex());
		}
		return null;
	}
}
